<template>
  <d2-container>
    <div class="flex-1 mx-2">
      <el-form :model="formCoupon" label-width="100px" ref="form">
        <div style="width: 40%;" class="mt-3">
          <el-form-item label="优惠券名称" prop="title">
            <el-input size="medium" v-model="formCoupon.title" placeholder="优惠券名称"></el-input>
          </el-form-item>
        </div>
        <div class="d-f">
          <div>
            <el-form-item label="优惠券金额" prop="discount_amount">
              <el-input-number size="medium" v-model="formCoupon.discount_amount" :precision="2" :min="0"
                :step="0.01"></el-input-number>
            </el-form-item>
          </div>
          <div class="ml-3">
            <el-form-item label="满金额使用" prop="minimum_order_amount">
              <el-input-number size="medium" v-model="formCoupon.minimum_order_amount" :precision="2" :min="0"
                :step="0.01"></el-input-number>
            </el-form-item>
          </div>
        </div>
        <div>
          <el-form-item label="派发数量" prop="coupon_count">
            <el-input-number size="medium" v-model="formCoupon.coupon_count" :min="0"></el-input-number>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="开始日期" prop="start_datetime">
            <el-date-picker size="medium" v-model="formCoupon.start_datetime" type="datetime" placeholder="开始时间"
              default-time="12:00:00">
            </el-date-picker>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="过期时间" prop="end_datetime">
            <el-date-picker v-model="formCoupon.end_datetime" type="datetime" placeholder="过期时间"
              default-time="12:00:00">
            </el-date-picker>
          </el-form-item>
        </div>
        <div style="width: 80%;">
          <el-form-item label="优惠券说明" prop="description">
            <el-input type="textarea" rows="3" v-model="formCoupon.description" placeholder="优惠券说明"></el-input>
          </el-form-item>
        </div>
        <div>
          <el-form-item label="参与商品" prop="coupon_range">
            <el-radio-group v-model="formCoupon.coupon_range">
              <el-radio :label="0">全场</el-radio>
              <el-radio :label="1">部分</el-radio>
            </el-radio-group>
          </el-form-item>
        </div>
        <el-card v-if="formCoupon.coupon_range === 1" style="margin-bottom: 20px" class="box-card">
          <div slot="header" class="clearfix">
            <span>优惠券商品</span>
            <el-button @click="selectCouponGoodsDialogVisible = true" style="float: right; padding: 3px 0"
              type="text">选择商品</el-button>
          </div>
          <el-table :data="formCoupon.products" border stripe size="medium">
            <el-table-column type="index" />
            <el-table-column align="center" label="图片" prop="image" width="80">
              <template slot-scope="scope">
                <el-popover placement="right" trigger="hover"
                  v-if="scope.row.image_list && scope.row.image_list !== '' && scope.row.image_list[0]">
                  <el-image slot="reference" style="width: 40px; height: 40px" :src="scope.row.image_list[0].url"
                    fit="cover" />
                  <el-image style="width: 220px; height: 220px" :src="scope.row.image_list[0].url" fit="cover" />
                </el-popover>
              </template>
            </el-table-column>
            <el-table-column label="商品名称" prop="product_name" />
            <el-table-column label="售价" prop="price" width="80" />
            <el-table-column label="操作" width="80" align="center">
              <template slot-scope="scope">
                <el-tooltip class="item" effect="dark" content="删除" placement="top">
                  <el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteSelectGoods(scope.$index)" />
                </el-tooltip>
              </template>
            </el-table-column>
          </el-table>
        </el-card>
        <div class="row" style="width: 80%;margin-top: 20px;">
          <el-form-item>
            <el-button plain @click="submitForm('drafts')">保存到草稿</el-button>
            <el-button type="primary" @click="addCoupon('submit')">保存并提交</el-button>
          </el-form-item>
        </div>
      </el-form>
    </div>
    <el-dialog title="选择商品" :visible.sync="selectCouponGoodsDialogVisible" width="70%">
      <el-table ref="multipleTable" class="mt-2" border stripe :data="productList" tooltip-effect="dark"
        style="width: 100%" @selection-change="goodsChange">
        <el-table-column align="center" label="全选" type="selection" width="55" />
        <el-table-column align="center" label="图片" prop="image" width="80">
          <template slot-scope="scope">
            <el-popover placement="right" trigger="hover"
              v-if="scope.row.image_list && scope.row.image_list !== '' && scope.row.image_list[0]">
              <el-image slot="reference" style="width: 30px; height: 30px" :src="scope.row.image_list[0].url"
                fit="cover" />
              <el-image style="width: 220px; height: 220px" :src="scope.row.image_list[0].url" fit="cover" />
            </el-popover>
          </template>
        </el-table-column>
        <el-table-column label="商品名称" prop="product_name" />
        <el-table-column label="售价" prop="price" width="80" />
      </el-table>
      <!-- 分页区域 -->
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page.sync="queryInfo.page" layout="total, prev, pager, next" :total="productTotal">
      </el-pagination>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="selectCouponGoodsDialogVisible = false">取 消</el-button>
          <el-button type="primary" @click="submitSelectGoodsList">确 定</el-button>
        </span>
      </template>
    </el-dialog>
  </d2-container>
</template>

<script>
  import {
    couponCreateUrl,
    couponUpdateUrl,
    couponDetailUrl
  } from '@/utils/promotion'
  import {
    productListUrl,
  } from '@/utils/product'
  import util from '@/libs/util.js'
  export default {
    data() {
      return {
        selectCouponGoodsDialogVisible: false,
        modifyStatus: false,
        queryInfo: {
          merchant_id: util.cookies.get('merchantId'),
          category_id: '',
          product_state: 0,
          page: 1,
          page_size: 10
        },
        options: [{
          value: 0,
          label: '全部商品'
        }, {
          value: 1,
          label: '部分商品'
        }],
        formCoupon: {
          title: '',
          description: '',
          start_datetime: '',
          end_datetime: '',
          merchant: util.cookies.get('merchantId'),
          coupon_count: '',
          coupon_residue: '',
          discount_amount: '',
          minimum_order_amount: '',
          coupon_range: 0,
          coupon_examine: 0,
          products: []
        },
        productTotal: 1,
        productList: [],
        selectGoodsList: [],
        product_ids: []
      }
    },
    mounted() {
      if (this.$route.query.couponId) {
        this.getCouponId = this.$route.query.couponId
        this.modifyStatus = true
        this.getCouponDetail()
      }
      this.getproductList()
    },
    methods: {
      getproductList() {
        this.$get(productListUrl, this.queryInfo).then(res => {
          this.productList = res.data.data.list
          this.productTotal = res.data.data.total
        })
      },
      // 分页页码显示条数
      handleSizeChange(newSize) {
        // 把每页显示多少数据重新赋值
        this.queryInfo.pageSize = newSize
        this.getproductList()
      },
      // 翻页事件
      handleCurrentChange(newPage) {
        this.queryInfo.page = newPage
        this.getproductList()
      },
      goodsChange(val) {
        this.selectGoodsList = val; // 直接将新添加的商品赋值给selectGoodsList
      },
      submitSelectGoodsList() {
        const goodsListArr = this.formCoupon.products.map(item => ({
          id: item.product,
          price: item.price,
          product_name: item.product_name,
          image_list: item.image_list
        }))
        const arr = [...this.selectGoodsList, ...goodsListArr]
        const res = new Map()
        this.formCoupon.products = arr.filter(arr => !res.has(arr.id) && res.set(arr.id, 1))
        this.product_ids = this.formCoupon.products.map(item => item.id)
        this.$refs.multipleTable.clearSelection()
        this.selectCouponGoodsDialogVisible = false
      },
      deleteSelectGoods(index) {
        this.$confirm('此操作将改商品从优惠券商品中移除, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          })
          .then(async () => {
            this.formCoupon.products.splice(index, 1)
            this.$message.success('删除成功')
            this.product_ids = this.formCoupon.products.map(item => item.product)
            this.selectGoodsList = this.selectGoodsList.filter(item => item.id !== this.formCoupon.products[index]
              .id)
            console.log(this.product_ids);
          })
          .catch(() => {
            this.$message.info('已取消删除')
          })
      },
      getCouponDetail() {
        this.$get(couponDetailUrl + this.getCouponId + '/').then(res => {
          if (res.data.code == 200) {
            this.formCoupon = {
              title: res.data.data.title,
              description: res.data.data.description,
              start_datetime: res.data.data.start_datetime,
              end_datetime: res.data.data.end_datetime,
              coupon_count: res.data.data.coupon_count,
              coupon_residue: res.data.data.coupon_residue,
              coupon_residue: res.data.data.coupon_residue,
              discount_amount: res.data.data.discount_amount,
              minimum_order_amount: res.data.data.minimum_order_amount,
              coupon_range: res.data.data.coupon_range,
              user: res.data.data.user,
              merchant: res.data.data.merchant,
              products: res.data.data.products
            }
          }
        })
      },
      addCoupon() {
        if (this.modifyStatus) {
          if (this.formCoupon.coupon_range === 1) {
            this.formCoupon.product_ids = this.product_ids;
          }
          console.log(this.formCoupon.product_ids);
          this.$put(couponUpdateUrl + this.getCouponId + '/', this.formCoupon).then(res => {
            if (res.data.code == 200) {
              this.$message.success('修改成功')
              this.formCoupon = {}
              setTimeout(() => {
                this.$router.go(-1)
              }, 300) // 延迟1秒执行
            }
          })
        } else {
          if (this.formCoupon.coupon_range === 1) {
            this.formCoupon.product_ids = this.product_ids;
          }
          console.log(this.formCoupon.product_ids);
          this.formCoupon.coupon_residue = this.formCoupon.coupon_count
          this.$post(couponCreateUrl, this.formCoupon).then(res => {
            if (res.data.code == 200) {
              this.$message.success('添加成功')
              this.formCoupon = {}
              setTimeout(() => {
                this.$router.go(-1)
              }, 300) // 延迟1秒执行
            }
          })
        }
      }
    }
  }
</script>

<style>
</style>